<template>
  <div>
    <input
      type="file"
      name="file"
      @change="changeFile"
    />
    <div
      id="wordView"
      v-html="wordText"
    />
  </div>
</template>

<script>
import mammoth from "mammoth";

export default {
  data () {
    return {
      wordText: "",
      wordURL: "",
    };
  },
  created () {
    this.getWordText();    //调用线上接口
  },
  methods: {
    //选择本地文件预览
    changeFile (event) {
      let that = this;
      let file = event.target.files[0];
      let reader = new FileReader(); // 读取文件内容
      reader.onload = function (loadEvent) { // 文件读取成功时触发
        let arrayBuffer = loadEvent.target.result; //arrayBuffer
        mammoth
          .convertToHtml({ arrayBuffer: arrayBuffer })
          .then(that.displayResult) // 调用页面渲染
          .done();
      };
      reader.readAsArrayBuffer(file);
    },
    //页面渲染
    displayResult (result) {
      console.log(result);
      this.wordText = result.value;
    },
    //调用后台文档下载接口
    getWordText () {
      let that = this;
      const xhr = new XMLHttpRequest();
      xhr.open("get", "https://xiaotianxia.github.io/blog/static/word%E6%96%87%E6%A1%A31.docx", true);
      xhr.responseType = "arraybuffer";
      xhr.onload = function () {
        console.log(xhr.response);
        if (xhr.status == 200) {
          mammoth
            .convertToHtml({ arrayBuffer: new Uint8Array(xhr.response) })
            .then(that.displayResult);
        }
      };
      xhr.send();
    },
  },
};
</script>
